package org.harsh.transmission.common;

import cn.hutool.core.codec.Base64;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.math.BigInteger;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class NodeQueue {
    /**
     * ipAddr - 通道信息
     */
    private static Map<String, Map<Integer, Channel>> channelMap = new ConcurrentHashMap<>();
    /**
     * ipAddr - NodeItem
     */
    private static Map<String, NodeItem> queue = new ConcurrentHashMap<>();

    private NodeQueue(){ }

    //判断当前通道是否已建立连接，且已交换密钥
    public synchronized static boolean checkChannelReady(String ipAddr) {
        return queue.containsKey(ipAddr);
    }

    public static synchronized void insert(String ipAddr, int port, Channel channel, BigInteger pubKey, BigInteger sharedKey){
        NodeItem nodeItem = new NodeItem(ipAddr, pubKey.toByteArray(), sharedKey.toByteArray());
        queue.put(ipAddr, nodeItem);
        if(channelMap.containsKey(ipAddr)) {
            Map channels = channelMap.get(ipAddr);
            channels.put(port, channel);
            channelMap.put(ipAddr, channels);
        } else {
            Map channels = new ConcurrentHashMap<>();
            channels.put(port, channel);
            channelMap.put(ipAddr, channels);
        }
    }

//    public static synchronized void insert(String id, NodeItem item) {
//        if(queue.containsKey(id)) {
//            log.error("{} is existed in node Map, item value is {}", id, item);
//        } else {
//            queue.put(id, item);
//        }
//    }

    public static synchronized void remove(String ipAddr) {
        if(queue.containsKey(ipAddr))
            queue.remove(ipAddr);
        if(channelMap.containsKey(ipAddr))
            channelMap.remove(ipAddr);
    }

    public static NodeItem get(String ipAddr) {
        if(ipAddr == null) {
            log.error("Queue id is null ");
            return null;
        }
        return queue.get(ipAddr);
    }

    /**
     * 获取Channel
     * @param ipAddr
     * @param port
     * @return
     */
    public static Channel getChannel(String ipAddr, int port) {
        if(queue.containsKey(ipAddr) && channelMap.containsKey(ipAddr)) {
            Map channels = channelMap.get(ipAddr);
            if(channels.containsKey(port))
                return (Channel)channels.get(port);
        }
        return null;
    }


}
